package blue.ocean.aop;

import blue.ocean.holder.DynamicDatasourceHolder;
import java.util.Objects;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Pointcut;
import org.aspectj.lang.reflect.MethodSignature;
import org.springframework.stereotype.Component;

@Component
@Aspect
public class DynamicDatasourceAspect {
    /**
     * 切点，切的是带有@DDS的注解
     */
    @Pointcut("@annotation(blue.ocean.aop.DDS)")
    public void dynamicDatasourcePointcut(){

    }
    /**
     * 环绕通知
     * @param joinPoint
     * @return
     * @throws Throwable
     */
    @Around("dynamicDatasourcePointcut()")
    public Object around(ProceedingJoinPoint joinPoint)throws Throwable{
        String datasourceKey="master";

        //类上的注解
        Class<?> targetClass=joinPoint.getTarget().getClass();
        DDS annotation=targetClass.getAnnotation(DDS.class);

        //方法上的注解
        MethodSignature methodSignature=(MethodSignature)joinPoint.getSignature();
        DDS annotationMethod=methodSignature.getMethod().getAnnotation(DDS.class);
        if(Objects.nonNull(annotationMethod)){
            datasourceKey=annotationMethod.value();
        }else{
            datasourceKey=annotation.value();
        }
        //设置数据源
        DynamicDatasourceHolder.setContextKey(datasourceKey);
        try{
            return joinPoint.proceed();
        }finally {
            DynamicDatasourceHolder.removeContextKey();
        }
    }
}
